//
//  DimensionalCardViewController.m
//  QRMaster
//
//  Created by liuyunlong on 15/11/10.
//  Copyright © 2015年 myApple. All rights reserved.
//

#import "DimensionalCardViewController.h"
#import "PromptInfoView.h"
#import "RequestNetWork.h"
#import "ZXMultiFormatWriter.h"
#import "ZXImage.h"
#import "ZXingObjC.h"
#import "LineView.h"
#import <ShareSDK/ShareSDK.h>
#import "PromptInfoView.h"
#import "OpertionPlist.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MZSelectableLabel.h"
#import "GetNameByID.h"
#import "faveriterCard.h"
#import "anaylsistDimensional.h"
#import "TouchBtnColor.h"
#import "EditShareTimeViewController.h"
#import "BackTableViewCell.h"
#import "StartPageController.h"
#import "setTimeModel.h"
#import "RoomTimeView.h"
#import "InternationalControl.h"
#import <MessageUI/MessageUI.h>

@interface DimensionalCardViewController ()<UIAlertViewDelegate,UIGestureRecognizerDelegate,UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate,MFMessageComposeViewControllerDelegate>
{
    UIImageView * HouseCardImgView;
    UILabel * houseCardLabel;
    UIImage * houseCardImg;//二维码图片
    UIImageView * logoImgView;//logo图片
    NSData * imgData;
    NSString * communityId;
    NSString * bulidingId;
    NSString * floorId;
    NSString * roomId;
    NSString * roomname;
    
    ShareUIView * shareView;  //分享view
    id<ISSContent> publishContent; //分享内容
    
    UIView * promtView;//提示view
    UIButton * faveritBtn;//收藏图片
    
    UILabel * communityNameLabel;
    UIView * nameLabelView;
    UITableView * backTabelView;
    CGRect backTabelViewFrame;
    UIView * allBackImgView;
    NSArray * backChooseArray;
    NSArray * backChooseImgArray;
    
    UIView * promtBackGroundView;
    UIView * helpView;
    
    NSMutableDictionary * tabbarInfo;//移动tabbar
    
    UIPageControl * pgctl;
    
    UISwipeGestureRecognizer *rightSwipeGestureRecognizer;
    UISwipeGestureRecognizer *leftSwipeGestureRecognizer;
    
    NSInteger index;//收藏数组的下标
    
    CGPoint houseCardImgCenter;//滑动时记住房卡的位置
    
    anaylsistDimensional * anaylsistDim;
    
    NSString * linkURLNO;
    NSString * sendMobile;    //要分享人的电话号码
    NSString *  currentLanagage;
    
    UITableView * haveTimeTabelView;
    NSMutableArray * haveTimeArray;
    UIView * shareBackView;
    NSData * shareLinkImgData;
    NSInteger communityManger;//组管理
    
    float value;//记住进来时屏幕的亮度
    RoomTimeView * timeView;
    UIButton * shareBtn;
    
    BOOL refreshFlag;//是否刷新要刷新（no表示从分享页面返回不刷新 yes则可以刷新）
    BOOL shakeFlag;//是否可以摇一摇，有手势密码时，不可以摇一摇
    
    //多语言
    UILabel * titleLabel;
    UILabel * cardLabel;
    UILabel * textLabel;
    MZSelectableLabel * MztextLabel;
    UILabel * helpLabel;
    UILabel * labelOne;
    UILabel * promtTextLabel;
}

@end

static SystemSoundID shake_sound_male_id = 0;

static SystemSoundID shake_sound_refresh = 1;

@implementation DimensionalCardViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        refreshFlag = YES;
        shakeFlag = YES;
        value = [UIScreen mainScreen].brightness;
        haveTimeArray = [[NSMutableArray alloc]init];
        backChooseImgArray = @[@"ic_share",@"ic_eye20"];
        shareLinkImgData = UIImageJPEGRepresentation([UIImage imageNamed:@"ic_锁掌柜_70"],1.0);
        index = 0;
        backChooseArray = @[NSLocalizedString(@"shareFriend", nil),NSLocalizedString(@"showCommunity", nil)];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(237, 238, 241, 1);
    tabbarInfo = [[NSMutableDictionary alloc]init];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(shareSound:) name:@"KCShakeSound" object:nil];
    [self prepareView];
    [self prepareBtnView];
    [self getCurrentLanagage];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hiddenKeyboard) name:@"KCHiddenKeyBoardNotification" object:nil];
}

-(void)shareSound:(NSNotification *)notInfo
{
    if ([notInfo.object isEqualToString:@"yes"]) {
        shakeFlag = YES;
    }
    else if ([notInfo.object isEqualToString:@"no"])
    {
        shakeFlag = NO;
    }
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
    shareBtn.hidden = NO;
    self.navigationItem.title = NSLocalizedString(@"qiuckCard", nil);
    backChooseArray = @[NSLocalizedString(@"shareFriend", nil),NSLocalizedString(@"showCommunity", nil)];
    communityNameLabel.text = NSLocalizedString(@"noQuitCard", nil);
    value = [UIScreen mainScreen].brightness;
    [[UIScreen mainScreen]setBrightness:1.0];
    [self getCardInfoByPlist:index];
    titleLabel.text = NSLocalizedString(@"qiuckCard", nil);
    cardLabel.text = NSLocalizedString(@"nowCardNum", nil);
    textLabel.text = NSLocalizedString(@"promtUserCard", nil);
    if ([[InternationalControl userLanguage]isEqualToString:@"en"]) {
        MztextLabel.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 200, MztextLabel.frame.origin.y,200, MztextLabel.frame.size.height);
    }
    else
    {
        MztextLabel.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 100, MztextLabel.frame.origin.y,100, MztextLabel.frame.size.height);
    }
    MztextLabel.text = NSLocalizedString(@"cardHelp", nil);
    NSMutableAttributedString * astr = [[NSMutableAttributedString alloc]initWithString:MztextLabel.text];
    [astr addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:12.0],NSFontAttributeName,RGBA(135, 199, 66, 1),NSForegroundColorAttributeName, nil] range:[MztextLabel.text rangeOfString:NSLocalizedString(@"forHelp", nil)]];
    MztextLabel.attributedText = astr;
    [MztextLabel setSelectableRange:[[MztextLabel.attributedText string]rangeOfString:NSLocalizedString(@"forHelp", nil)]];
    helpLabel.text = NSLocalizedString(@"help", nil);
    labelOne.text = NSLocalizedString(@"cardHelpContent", nil);
    promtTextLabel.text = NSLocalizedString(@"noDeflutCard", nil);
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[UIScreen mainScreen] setBrightness:value];
    shareBtn.hidden = YES;
    [self stopWaiting];
    [self resignFirstResponder];
}


#pragma mark  ---- 注册声音到系统
-(void)playSound
{
    NSString * path = [[NSBundle mainBundle]pathForResource:@"5018" ofType:@"wav"];
    if (path) {
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &shake_sound_male_id);
        AudioServicesPlayAlertSound(shake_sound_male_id);
    }
}

-(void)playRefreshSound
{
    NSString * path = [[NSBundle mainBundle]pathForResource:@"shake_match" ofType:@"mp3"];
    if (path) {
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &shake_sound_refresh);
        AudioServicesPlayAlertSound(shake_sound_refresh);
    }
}

-(BOOL)canBecomeFirstResponder
{
    return YES;
}

-(void)getCardInfoByPlist:(NSInteger)count
{
    NSMutableDictionary * dict = [OpertionPlist readDataFromPlist];
    NSMutableArray * cardInfoArray = [dict objectForKey:FAVERITCARD];
    if (cardInfoArray.count > count) {
        communityId = [cardInfoArray[count] objectForKey:@"communityId"];
        floorId = [cardInfoArray[count] objectForKey:@"floorId"];
        NSString * floorName = [cardInfoArray[count]objectForKey:@"floorName"];
        bulidingId = [cardInfoArray[count] objectForKey:@"buildId"];
        NSString * bulidingName = [cardInfoArray[count]objectForKey:@"buildName"];
        roomId = [cardInfoArray[count] objectForKey:@"roomId"];
        roomname = [cardInfoArray[count] objectForKey:@"roomName"];
        houseCardLabel.text = roomname;
        communityNameLabel.text = [NSString stringWithFormat:@"%@%@%@",[cardInfoArray[count] objectForKey:@"communityName"],bulidingName,floorName];
        communityManger = [[cardInfoArray[count] objectForKey:@"groupMId"]intValue];
    }
    if (cardInfoArray.count == 0) {
        roomId = nil;//可能收藏了，但是在别的地方取消了，所以每次进来都要判断
    }
    pgctl.numberOfPages = cardInfoArray.count;
    if (!roomId) {
        promtView.hidden = NO;
        return;
    }
    else
    {
        promtView.hidden = YES;
        faveritBtn.selected = NO;
    }
    //判断是不是组管理
    if (communityId) {
        NSDictionary * communityInfo = [OpertionPlist readDataFromPlist];
        NSArray * communityArr = [communityInfo objectForKey:COMMUNITYINFOFORKEY];
        if (communityArr.count > 0) {
            for (NSDictionary * dict in communityArr) {
                if ([[dict objectForKey:@"communityid"]isEqualToString:communityId]) {
                    communityManger = [[dict objectForKey:@"groupMId"]integerValue];
                }
            }
        }
    }
    if (refreshFlag) {
         [self getcheckAuthDatatime];
    }
    else
    {
        refreshFlag = YES;
    }
}

-(void)prepareView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = UI_SCREEN_HEIGHT;
    float x = ScreenWidth - 40;
    float y = 2;
    float width = 40;
    float height = 40;
    
    shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shareBtn.frame = CGRectMake(x, y, width, height);
    [shareBtn addTarget:self action:@selector(addClick) forControlEvents:UIControlEventTouchUpInside];
    [shareBtn setImage:[UIImage imageNamed:@"ic_add30"] forState:0];
    [shareBtn setBackgroundImage:[TouchBtnColor imageWithColor:[UIColor grayColor] size:shareBtn.frame.size] forState:UIControlStateHighlighted];
    [self.navigationController.navigationBar addSubview:shareBtn];
    
    x = 20;
    y = 40;
    width = ScreenWidth - x * 2;
    height = width;
    if (UI_SCREEN_HEIGHT == 480) {
        y = 0;
        width = ScreenWidth - x * 2;
        height = width;
    }
    UIImageView * houseCardBackView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    houseCardBackView.userInteractionEnabled = YES;
    houseCardBackView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:houseCardBackView];
    
    
    //二维码房卡
    x = houseCardBackView.frame.size.width / 2.0 - 90;
    y = houseCardBackView.frame.size.height / 2.0 - 90;
    width = 180;
    height = 180;
    HouseCardImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    HouseCardImgView.userInteractionEnabled = YES;
    HouseCardImgView.image = [UIImage imageNamed:@"房卡有权限"];
    houseCardImgCenter = HouseCardImgView.center;
    [houseCardBackView addSubview:HouseCardImgView];
    
    UITapGestureRecognizer * refreshImgTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(refreshClick:)];
    [HouseCardImgView addGestureRecognizer:refreshImgTap];
    
    leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];
    rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];
    
    leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    
    [HouseCardImgView addGestureRecognizer:leftSwipeGestureRecognizer];
    [HouseCardImgView addGestureRecognizer:rightSwipeGestureRecognizer];
    
    pgctl = [[UIPageControl alloc]initWithFrame:CGRectMake(houseCardBackView.frame.size.width / 2.0 - 30,houseCardBackView.frame.size.height - 60, 60, 30)];
    pgctl.currentPageIndicatorTintColor = RGBA(152, 194, 52, 1);
    pgctl.pageIndicatorTintColor = RGBA(237, 238, 241, 1);
    [houseCardBackView addSubview:pgctl];
    
    logoImgView = [[UIImageView alloc]initWithFrame:CGRectMake(HouseCardImgView.frame.size.width / 2.0 - 15, HouseCardImgView.frame.size.height / 2.0 - 15, 30, 30)];
    logoImgView.image = [UIImage imageNamed:@"ic_锁掌柜_70"];
    logoImgView.hidden = YES;
    [HouseCardImgView addSubview:logoImgView];
    
    x = 0;
    width = houseCardBackView.frame.size.width;
    y = houseCardBackView.frame.size.height - 40;
    height = 40;
    UIView * cardView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    cardView.backgroundColor = RGBA(135, 199, 66, 1);
    [houseCardBackView addSubview:cardView];
    
    x = 10;
    y = 10;
    height = 20;
    width = 80;
    cardLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    cardLabel.text = NSLocalizedString(@"nowCardNum", nil);
    cardLabel.font = [UIFont systemFontOfSize:14.0];
    cardLabel.textColor = [UIColor whiteColor];
    [cardView addSubview:cardLabel];
    
    x = 80;
    width = cardView.frame.size.width - x - 20;
    houseCardLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    houseCardLabel.text = roomname;
    houseCardLabel.font = [UIFont systemFontOfSize:14.0];
    houseCardLabel.textColor = [UIColor whiteColor];
    [cardView addSubview:houseCardLabel];
    
    faveritBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    faveritBtn.frame = CGRectMake(cardView.frame.size.width - 80, 5, 30, 30);
    [faveritBtn setBackgroundImage:[UIImage imageNamed:@"ic_heartfilled"] forState:0];
    [faveritBtn addTarget:self action:@selector(clickImg:) forControlEvents:UIControlEventTouchUpInside];
    [cardView addSubview:faveritBtn];
    
    UIButton * timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    timeBtn.frame = CGRectMake(cardView.frame.size.width - 40, 5, 30, 30);
    [timeBtn setBackgroundImage:[UIImage imageNamed:@"ic_time30white"] forState:0];
    [timeBtn addTarget:self action:@selector(lookTime) forControlEvents:UIControlEventTouchUpInside];
    [cardView addSubview:timeBtn];
    
    x = houseCardBackView.frame.origin.x;
    y = houseCardBackView.frame.origin.y + houseCardBackView.frame.size.height + 5;
    width = cardView.frame.size.width;
    height = 40;
    if (UI_SCREEN_HEIGHT == 480) {
        height = 40;
        y -= 5;
    }
    textLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    textLabel.text = NSLocalizedString(@"promtUserCard", nil);
    textLabel.numberOfLines = 0;
    textLabel.font = [UIFont systemFontOfSize:14.0];
    textLabel.textColor = RGBA(135, 199, 66, 1);
    [self.view addSubview:textLabel];
    
    //帮助提示
    y = textLabel.frame.size.height + textLabel.frame.origin.y + 3;
    height = 30;
    if ([[InternationalControl userLanguage]isEqualToString:@"en"]) {
        x = ScreenWidth - 200;
        width = 200;
    }
    else
    {
        x = ScreenWidth - 100;
        width = 100;
    }
    MztextLabel = [[MZSelectableLabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    MztextLabel.text = NSLocalizedString(@"cardHelp", nil);
    MztextLabel.font = [UIFont systemFontOfSize:12.0];
    MztextLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:MztextLabel];
    
    __weak DimensionalCardViewController * weakSelf = self;
    MztextLabel.selectionHandler = ^(NSRange range,NSString * string)
    {
        [weakSelf helps];
    };
    
    NSMutableAttributedString * astr = [[NSMutableAttributedString alloc]initWithString:MztextLabel.text];
    [astr addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:12.0],NSFontAttributeName,RGBA(152, 194, 52, 1),NSForegroundColorAttributeName, nil] range:[MztextLabel.text rangeOfString:NSLocalizedString(@"forHelp", nil)]];
    MztextLabel.attributedText = astr;
    [MztextLabel setSelectableRange:[[MztextLabel.attributedText string]rangeOfString:NSLocalizedString(@"forHelp", nil)]];
    
    x = 0;
    y = 0;
    width = ScreenWidth;
    height = 40;
    nameLabelView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    nameLabelView.backgroundColor = RGBA(255, 255, 204, 1);
    [self.view addSubview:nameLabelView];
    x = 40;
    y = 0;
    width = ScreenWidth - 80;
    communityNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    communityNameLabel.text = NSLocalizedString(@"noQuitCard", nil);
    communityNameLabel.numberOfLines = 2;
    communityNameLabel.font = [UIFont systemFontOfSize:14.0];
    communityNameLabel.textColor = [UIColor blackColor];
    communityNameLabel.textAlignment = NSTextAlignmentCenter;
    [nameLabelView addSubview:communityNameLabel];
    
    x = ScreenWidth - 40;
    y = 0;
    width = 40;
    height = 40;
    UIButton * communityNameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    communityNameBtn.frame = CGRectMake(x, y, width, height);
    [communityNameBtn setImage:[UIImage imageNamed:@"ic_close20"] forState:0];
    [communityNameBtn addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    [nameLabelView addSubview:communityNameBtn];
    
    x = 0;
    y = 0;
    width = ScreenWidth;
    height = ScreenHeight;
    promtBackGroundView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    promtBackGroundView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
    promtBackGroundView.hidden = YES;
    [self.view addSubview:promtBackGroundView];
    
    UITapGestureRecognizer * backTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeBackView)];
    [promtBackGroundView addGestureRecognizer:backTap];
    
    x = ScreenWidth;
    y = promtBackGroundView.frame.size.height;
    height = 200;
    width =ScreenWidth;
    helpView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    helpView.backgroundColor = [UIColor whiteColor];
    helpView.hidden = YES;
    [promtBackGroundView addSubview:helpView];
    
    timeView = [[RoomTimeView alloc]init];
    timeView.frame = helpView.frame;
    timeView.hidden = YES;
    timeView.backgroundColor = [UIColor whiteColor];
    [promtBackGroundView addSubview:timeView];
    
    x = ScreenWidth /10;
    width = 80;
    y = 20;
    height = 20;
    helpLabel =[[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    helpLabel.text = NSLocalizedString(@"help", nil);
    helpLabel.font = [UIFont boldSystemFontOfSize:18.0];
    helpLabel.textColor = RGBA(153, 153, 153, 1);
    helpLabel.textAlignment = NSTextAlignmentCenter;
    [helpView addSubview:helpLabel];
    
    y += height + 15;
    width = ScreenWidth - 2 * x;
    height = 120;
    labelOne = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    labelOne.text = NSLocalizedString(@"cardHelpContent", nil);
    labelOne.numberOfLines = 0;
    labelOne.font = [UIFont systemFontOfSize:14.0];
    [helpView addSubview:labelOne];
    
    //没有收藏房间的提示
    promtView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    promtView.backgroundColor = RGBA(237, 238, 241, 1);
    promtView.hidden = YES;
    [self.view addSubview:promtView];
    
    NSString * imgPath = [[NSBundle mainBundle]pathForResource:@"没有设置默认房卡" ofType:@"png"];
    UIImage * promImg = [UIImage imageWithContentsOfFile:imgPath];
    height= promImg.size.height * ScreenWidth / 3.0 /promImg.size.width;
    width = ScreenWidth / 3.0;
    UIImageView * promImgView = [[UIImageView alloc]initWithFrame:CGRectMake((UI_SCREEN_WIDTH - width)/ 2.0, (UI_SCREEN_HEIGHT - height)/ 2.0 - 64, width, height)];
    promImgView.image = promImg;
    [promtView addSubview:promImgView];
    
    
    promtTextLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, promImgView.frame.size.height /2.0+promImgView.frame.origin.y + 74, ScreenWidth - 100, 60)];
    promtTextLabel.text = NSLocalizedString(@"noDeflutCard", nil);
    promtTextLabel.textColor = RGBA(211, 211, 211, 1);
    promtTextLabel.textAlignment = NSTextAlignmentCenter;
    promtTextLabel.numberOfLines = 0;
    promtTextLabel.font = [UIFont systemFontOfSize:16.0];
    [promtView addSubview:promtTextLabel];
    titleLabel.text = NSLocalizedString(@"qiuckCard", nil);
    
    shareView = [[ShareUIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    shareView.delegate = self;
    shareView.hidden = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:shareView];
}

-(void)cancel
{
    nameLabelView.hidden = YES;
}

-(void)prepareBtnView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight;
    allBackImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    allBackImgView.userInteractionEnabled = YES;
    allBackImgView.hidden = YES;
    [self.view addSubview:allBackImgView];
    UITapGestureRecognizer * tapAllBackView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addClick)];
    tapAllBackView.delegate = self;
    [allBackImgView addGestureRecognizer:tapAllBackView];
    
    x = allBackImgView.frame.size.width - 34;
    y = 2;
    width = 11;
    height = 8;
    UIImageView * triangleView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    triangleView.image = [UIImage imageNamed:@"triangle"];
    triangleView.backgroundColor = [UIColor clearColor];
    [allBackImgView addSubview:triangleView];
    
    x = ScreenWidth - 144;
    y = 10;
    width = 138;
    height = backChooseArray.count * 40;
    backTabelView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    backTabelView.dataSource = self;
    backTabelView.delegate = self;
    backTabelView.bounces = NO;
    backTabelView.layer.cornerRadius = 2;
    backTabelView.layer.masksToBounds = YES;
    backTabelView.userInteractionEnabled = YES;
    backTabelView.separatorStyle = NO;
    [allBackImgView addSubview:backTabelView];
    backTabelViewFrame = backTabelView.frame;
}

#pragma mark -- 解决tableview中手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return backChooseArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellString = @"cell";
    BackTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellString];
    if (!cell) {
        cell = [[BackTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellString];
    }
    cell.contentView.backgroundColor = RGBA(34, 41, 44, 1);
    cell.selectedBackgroundView = [[UIImageView alloc]initWithFrame:cell.frame];
    cell.selectedBackgroundView.backgroundColor = [UIColor blackColor];
    cell.imgString = backChooseImgArray[indexPath.row];
    cell.content = backChooseArray[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //如果是总控卡的话
    if ([roomId isEqualToString:[NSString stringWithFormat:@"-%@",communityId]]) {
        nameLabelView.hidden = NO;
    }
    else
    {
        if (indexPath.row == 0) {
            [self ShareClick];
        }
        else
        {
            nameLabelView.hidden = NO;
        }
    }
    
    [self addClick];
    [backTabelView deselectRowAtIndexPath:[backTabelView indexPathForSelectedRow] animated:YES];
}


#pragma mark -- 点击➕号
-(void)addClick
{
    if ([roomId isEqualToString:[NSString stringWithFormat:@"-%@",communityId]])
    {
        backChooseArray = @[NSLocalizedString(@"showCommunity", nil)];
        backChooseImgArray = @[@"ic_eye20"];
        backTabelView.frame = CGRectMake(backTabelView.frame.origin.x, backTabelView.frame.origin.y, backTabelView.frame.size.width, backChooseArray.count * 40);
    }
    else
    {
        backChooseArray = @[NSLocalizedString(@"shareFriend", nil),NSLocalizedString(@"showCommunity", nil)];
        backChooseImgArray = @[@"ic_share",@"ic_eye20"];
        backTabelView.frame = CGRectMake(backTabelView.frame.origin.x, backTabelView.frame.origin.y, backTabelView.frame.size.width, backChooseArray.count * 40);
    }
    [backTabelView reloadData];
    CGRect replaceRect = backTabelViewFrame;
    if (!allBackImgView.hidden) {
        replaceRect.origin.x = replaceRect.origin.x + 80;
        replaceRect.size.width = replaceRect.size.width / 4.0;
        replaceRect.size.height = 0;
        [UIView animateWithDuration:0.1 animations:^{
            backTabelView.frame = replaceRect;
            backTabelView.alpha = 0;
        } completion:^(BOOL finished) {
            backTabelView.frame = backTabelViewFrame;
            allBackImgView.hidden = !allBackImgView.hidden;
        }];
    }
    else
    {
        allBackImgView.hidden = !allBackImgView.hidden;
        backTabelView.alpha = 1;
    }
}

//帮助提示
-(void)helps
{
    promtBackGroundView.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
    helpView.hidden = NO;
    [tabbarInfo setValue:@"1" forKey:@"moveOrBack"];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"moveTabbarOrNot" object:nil userInfo:tabbarInfo];
    
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame = helpView.frame;
        frame.origin.y = promtBackGroundView.frame.size.height - 260;
        frame.origin.x = 0;
        helpView.frame = frame;
    } completion:^(BOOL finished) {
        
    }];
}

//移除帮助提示
-(void)removeBackView
{
    
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame = helpView.frame;
        frame.origin.y = promtBackGroundView.frame.size.height;
        frame.origin.x = -[UIScreen mainScreen].bounds.size.width;
        helpView.frame = frame;
        CGRect timeFrame = timeView.frame;
        timeFrame.origin.y = promtBackGroundView.frame.size.height;
        timeFrame.origin.x = -[UIScreen mainScreen].bounds.size.width;
        timeView.frame = timeFrame;
    } completion:^(BOOL finished) {
        promtBackGroundView.hidden = YES;
        helpView.hidden = YES;
        timeView.hidden = YES;
        self.tabBarController.tabBar.hidden = NO;
        helpView.frame = CGRectMake([UIScreen mainScreen].bounds.size.width, helpView.frame.origin.y, helpView.frame.size.width, helpView.frame.size.height);
        timeView.frame = CGRectMake([UIScreen mainScreen].bounds.size.width, helpView.frame.origin.y, helpView.frame.size.width, helpView.frame.size.height);
        [tabbarInfo setValue:@"0" forKey:@"moveOrBack"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"moveTabbarOrNot" object:nil userInfo:tabbarInfo];
    }];
}

#pragma mark - 点击取消收藏
-(void)clickImg:(UIButton *)btn
{
    
    [self startWaiting:nil color:nil addToView:self.view];
    NSMutableDictionary * dict = [[NSMutableDictionary alloc]init];
    [dict setValue:communityId forKey:@"communityId"];
    [dict setValue:roomId forKey:@"roomId"];
    [dict setValue:bulidingId forKey:@"buildId"];
    [dict setValue:floorId forKey:@"floorId"];
    [dict setValue:roomname forKey:@"roomName"];
    [faveriterCard faveriterOrCancelCardByRoomId:dict result:^(cardResultType type) {
        [self stopWaiting];
        switch (type)
        {
            case KCSUCCESS_FAVERITER:
                [PromptInfoView showMessage:NSLocalizedString(@"collectCardSuccess", nil)];
                [btn setBackgroundImage:[UIImage imageNamed:@"ic_heartfilled"] forState:0];
                break;
            case KCFAIL_FAVERITER:
                [PromptInfoView showMessage:NSLocalizedString(@"collectCount", nil)];
                break;
            case KCCANCEL_FAVERITER:
                [PromptInfoView showMessage:NSLocalizedString(@"cancleCardCollect", nil)];
                [faveritBtn setBackgroundImage:[UIImage imageNamed:@"ic_heart"] forState:0];
                break;
        }
        roomId = nil;
        if (index != 0) {
            index --;
            [self getCardInfoByPlist:index];
        }
        else
        {
            [self getCardInfoByPlist:0];
        }
        
    }];
}

//显示时间
-(void)lookTime
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:communityId forKey:@"communityId"];
    [postDict setValue:roomId forKey:@"roomId"];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [rnk initWithPath:POST(GETMYSELFROOMTINE) params:postDict block:^(id downLoadData, id error) {
        [self stopWaiting];
        id data = [downLoadData objectForKey:@"data"];
        if (data != nil) {
            if ([[data objectForKey:@"flag"]intValue] == 0)
            {
                NSMutableArray * timeDataArray = [[NSMutableArray alloc]init];
                NSArray * listArray = [data objectForKey:@"list"];
                for (NSDictionary * dict in listArray)
                {
                    setTimeModel * model = [[setTimeModel alloc]init];
                    model.beginTime = [dict objectForKey:@"startTime"];
                    model.endTime = [dict objectForKey:@"endTime"];
                    model.weekInfo = [dict objectForKey:@"cycleString"];
                    model.timeId = [dict objectForKey:@"id"];
                    [timeDataArray addObject:model];
                }
                if (timeDataArray.count == 0) {
                    [PromptInfoView showMessage:NSLocalizedString(@"noTimeOpenRoom", nil) superView:self.view];
                }
                else
                {
                    promtBackGroundView.hidden = NO;
                    timeView.hidden = NO;
                    self.tabBarController.tabBar.hidden = YES;
                    [tabbarInfo setValue:@"1" forKey:@"moveOrBack"];
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"moveTabbarOrNot" object:nil userInfo:tabbarInfo];
                    [UIView animateWithDuration:0.5 animations:^{
                        CGRect frame = timeView.frame;
                        frame.origin.y = promtBackGroundView.frame.size.height - (timeDataArray.count * 55 + 140);
                        frame.origin.x = 0;
                        timeView.frame = frame;
                        timeView.timeData = timeDataArray;
                    } completion:^(BOOL finished) {
                        
                    }];
                }
            }
            else
            {
                
                [PromptInfoView showMessage:NSLocalizedString(@"allTimeOpen", nil) superView:self.view];
            }
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
        }
    }];
    
}


//点击图片刷新
-(void)refreshClick:(UITapGestureRecognizer *)tap
{
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(getcheckAuthDatatime) object:tap];
    [self performSelector:@selector(getcheckAuthDatatime) withObject:tap afterDelay:0.3f];
    //    [self getcheckAuthDatatime];
}

#pragma mark -- 左右滑动
- (void)handleSwipes:(UISwipeGestureRecognizer *)sender
{
    if (sender.direction == UISwipeGestureRecognizerDirectionLeft) {
        
        if (index < pgctl.numberOfPages - 1) {
            CGPoint center = HouseCardImgView.center;
            center.x -= 40;
            [UIView animateWithDuration:0.5 animations:^{
                HouseCardImgView.center = center;
                HouseCardImgView.alpha = 0;
            } completion:^(BOOL finished) {
                CGPoint centerTwo = houseCardImgCenter;
                centerTwo.x += 40;
                HouseCardImgView.center = centerTwo;
                [UIView animateWithDuration:0.5 animations:^{
                    HouseCardImgView.alpha = 1;
                    HouseCardImgView.center = houseCardImgCenter;
                    index ++;
                    [self getCardInfoByPlist:index];
                    pgctl.currentPage = index;
                } completion:^(BOOL finished) {
                    
                }];
                
            }];

        }
        
    }
    
    if (sender.direction == UISwipeGestureRecognizerDirectionRight) {
        
        if (index > 0) {
            CGPoint center = HouseCardImgView.center;
            center.x += 40;
            [UIView animateWithDuration:0.5 animations:^{
                HouseCardImgView.center = center;
                HouseCardImgView.alpha = 0;
            } completion:^(BOOL finished) {
                CGPoint centerTwo = houseCardImgCenter;
                centerTwo.x -= 40;
                HouseCardImgView.center = centerTwo;
                [UIView animateWithDuration:0.5 animations:^{
                    HouseCardImgView.alpha = 1;
                    HouseCardImgView.center = houseCardImgCenter;
                    index --;
                    [self getCardInfoByPlist:index];
                    pgctl.currentPage = index;
                } completion:^(BOOL finished) {
                    
                }];
                
            }];
            
        }
    }
    
    
}

#pragma mark -- 获取当前语言
-(void)getCurrentLanagage
{
    currentLanagage = [InternationalControl userLanguage];
    if ([currentLanagage isEqualToString:@"zh-Hans-CN"]) {
        currentLanagage = @"zh_cn";
    }
    else if([currentLanagage isEqualToString:@"zh-Hant-HK"])
    {
        currentLanagage = @"zh_tw";
    }
    else if([currentLanagage isEqualToString:@"zh-Hant"])
    {
        currentLanagage = @"zh_tw";
    }
    else if([currentLanagage isEqualToString:@"en"])
    {
        currentLanagage = @"en_us";
    }
    else
    {
        currentLanagage = @"zh_cn";
    }
}

-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (roomId && shakeFlag) {
        [self playSound];
    }
}

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (roomId) {
        [self getcheckAuthDatatime];
    }
}

-(void)shareType
{
    //构造分享内容
    publishContent  = [ShareSDK content:NSLocalizedString(@"shareContent", nil)
                         defaultContent:NSLocalizedString(@"shareDefualt", nil)
                                  image:[ShareSDK imageWithData:imgData fileName:@"image" mimeType:@"jpg"]
                                  title:NSLocalizedString(@"shareTitle", nil)
                                    url:nil
                            description:nil
                              mediaType:SSPublishContentMediaTypeImage];
    [publishContent addQQUnitWithType:[NSNumber numberWithInt:SSPublishContentMediaTypeNews] content:NSLocalizedString(@"shareContent", nil) title:NSLocalizedString(@"shareTitle", nil) url:[NSString stringWithFormat:@"%@",linkURLNO] image:[ShareSDK imageWithData:shareLinkImgData fileName:@"image" mimeType:@"jpg"]];
    [publishContent addWeixinSessionUnitWithType:[NSNumber numberWithInt:SSPublishContentMediaTypeNews] content:NSLocalizedString(@"shareContent", nil) title:NSLocalizedString(@"shareTitle", nil) url:[NSString stringWithFormat:@"%@",linkURLNO] image:[ShareSDK imageWithData:shareLinkImgData fileName:@"image" mimeType:@"jpg"] musicFileUrl:nil extInfo:nil fileData:nil emoticonData:nil];

    shareView.hidden = NO;
}

#pragma mark ----- 分享点击图片事件
-(void)shareClick:(NSInteger)shareIndex
{
    [self cancelShare];
    int shareType = 0;
    if (shareIndex == 2) {
        [self sendSMS];
        return;
    }
    else if (shareIndex == 0) {
        shareType = ShareTypeQQ;
    }
    else if (shareIndex == 1)
    {
        shareType = ShareTypeWeixiSession;
    }
    
    [ShareSDK showShareViewWithType:shareType container:nil content:publishContent statusBarTips:YES authOptions:nil shareOptions:nil result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        if (state == SSResponseStateFail)
        {
            [PromptInfoView showMessage:NSLocalizedString(@"shareFail", nil)] ;
        }

    }];
}

#pragma mark ------取消分享
-(void)cancelShare
{
    shareView.hidden = YES;
}

#pragma mark --------  发送短信
-(void)sendSMS
{
    if ([MFMessageComposeViewController canSendText]) {
        MFMessageComposeViewController * messageController = [[MFMessageComposeViewController alloc]init];
        messageController.delegate = self;
        messageController.messageComposeDelegate = self;
        NSString * messageContent = [NSString stringWithFormat:@"%@%@%@",NSLocalizedString(@"messageFirst", nil), linkURLNO,NSLocalizedString(@"messageSecond", nil)];
        messageController.body = messageContent;
        messageController.recipients = @[sendMobile];
        [self presentViewController:messageController animated:YES completion:^{
            [self cancelShare];
        }];
    }
    else
    {
        [PromptInfoView showMessage:NSLocalizedString(@"shareFail", nil)] ;
    }
   
}

-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
     [self dismissViewControllerAnimated:YES completion:nil];
//    if (result == MessageComposeResultCancelled) {
//        [self dismissViewControllerAnimated:YES completion:nil];
//    }
}


#pragma mark - 获取二维码
-(void)getcheckAuthDatatime
{
    if ([self IsHaveNetwork]) {
        return;
    }
     [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:communityId forKey:@"communityId"];
    [postDict setValue:bulidingId forKey:@"buildingId"];
    [postDict setValue:floorId forKey:@"floorId"];
    [postDict setValue:roomId forKey:@"roomId"];
    [postDict setValue:@"0" forKey:@"validTime"];
    [postDict setValue:@"3" forKey:@"type"];
    NSString * postURLString = nil;
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    if ([roomId isEqualToString:[NSString stringWithFormat:@"-%@",communityId]]) {
        NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
        [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
        [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
        [postDict setValue:communityId forKey:@"communityId"];
        postURLString = POST(CONTROLCARD);
    }
    else
    {
         postURLString = POST(CHECKAUTHORTIY);
    }
    [rnk initWithPath:postURLString params:postDict block:^(id downLoadData, id error) {
         [self stopWaiting];
        id data = [downLoadData objectForKey:@"data"];
        if (data != nil) {
            if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"sound"] isEqualToString:@"1"]) {
                [self playRefreshSound];
            }
            HouseCardImgView.image = nil;
            logoImgView.hidden = YES;
            houseCardImg = nil;
            NSString * string = [data objectForKey:@"cardString"];
            anaylsistDim = [[anaylsistDimensional alloc]init];
            NSString * encodeString = [anaylsistDim stringFromHexString:string];
            ZXImage * image = [anaylsistDim prepareCardView:encodeString addImgView:HouseCardImgView];
            if (image)
            {
                HouseCardImgView.image = [UIImage imageWithCGImage:image.cgimage];
                houseCardImg = [UIImage imageWithCGImage:image.cgimage];
                imgData = UIImageJPEGRepresentation(houseCardImg, 1.0);
                logoImgView.hidden = NO;
            }
            else
            {
                HouseCardImgView.image = [UIImage imageNamed:@"splash"];
                houseCardImg = nil;
                logoImgView.hidden = YES;
            }
        }
        else
        {
            
            [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
            HouseCardImgView.image = [UIImage imageNamed:@"splash"];
            houseCardImg = nil;
            logoImgView.hidden = YES;
        }
    }];

    [faveritBtn setBackgroundImage:[UIImage imageNamed:@"ic_heartfilled"] forState:0];
}

//分享点击事件
-(void)ShareClick
{
    if (communityManger == 1) {
        [PromptInfoView showMessage:NSLocalizedString(@"你暂时没有分享权力", nil)];
        return;
    }
    if (!roomId) {
        [PromptInfoView showMessage:NSLocalizedString(@"noCollectCard", nil)];
        return;
    }
    EditShareTimeViewController * estvc = [[EditShareTimeViewController alloc]init];
    estvc.communityId = communityId;
    estvc.roomId = roomId;
    estvc.surePost = ^(NSString * result,NSString * mobile)
    {
        refreshFlag = NO;
        linkURLNO = result;
        sendMobile = mobile;
        [self shareType];
    };
    estvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:estvc animated:YES];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"KCShakeSound" object:nil];
}

-(void)hiddenKeyboard
{
    [self resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
